package com.henrik.bak.esportcalendar.utils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import android.content.Context;
import android.util.Log;

import com.henrik.bak.esportcalendar.model.Day;
import com.henrik.bak.esportcalendar.model.Event;
import com.henrik.bak.esportcalendar.model.Month;

public class CalendarUtils {
	static ArrayList<String> startDates = new ArrayList<String>();
	static ArrayList<Event> events = new ArrayList<Event>();
	com.henrik.bak.esportcalendar.model.Calendar calendar;
	static Set<Event> userEvents = new HashSet<Event>();

	public static Set<Event> getUserEvents() {
		return userEvents;
	}

	public static void setUserEvents(Set<Event> userEvents) {
		CalendarUtils.userEvents = userEvents;
	}

	public ArrayList<String> getStartDates() {
		return startDates;
	}

	public void setStartDates(ArrayList<String> startDates) {
		CalendarUtils.startDates = startDates;
	}

	public ArrayList<Event> getEvents() {
		return events;
	}

	public void setEvents(ArrayList<Event> events) {
		CalendarUtils.events = events;
	}

	public com.henrik.bak.esportcalendar.model.Calendar getCalendar() {
		return calendar;
	}

	public void setCalendar(
			com.henrik.bak.esportcalendar.model.Calendar calendar) {
		this.calendar = calendar;
	}

	public void readCalendarEvent(Context context, String timezone,
			Set<String> selectedGames) {

		// fetching calendars id
		startDates.clear();

		for (Month month : calendar.getMonth()) {
			for (Day day : month.getDay()) {
				for (Event event : day.getEvent()) {
					if (selectedGames.contains(event.getType())) {
						Integer currentYear = month.getYear();
						Integer currentMonth = month.getNum();
						Integer currentDay = day.getNum();

						DateTime originalTime = new DateTime(currentYear,
								currentMonth, currentDay, event.getHour(),
								event.getMinute(),
								DateTimeZone.forID("Asia/Seoul"));
						DateTime convertedTime = new DateTime(originalTime,
								DateTimeZone.forID(timezone));

						event.setEventDate(convertedTime);
						events.add(event);

						startDates.add(createDate(convertedTime));
					}
				}
			}
		}
		
		for (Event event : userEvents) {
			if (!events.contains(event)) {
				events.add(event);
				startDates.add(createDate(event.getEventDate()));
				Log.d("ESPORTS", "user event scanned, added: "+event.toString());
			}
		}
	}

	public String createDate(DateTime timeToConvert) {

		DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd");
		return timeToConvert.toString(formatter);
	}
}